<?php

namespace Common\Logic;

use Think\Controller;

/**
 * Description of HotelApplyLogic.class控制器实例
 * 
 * @author songanwei
 * @date 2016-1-5
 */
class HotelApplyLogic extends Controller {

    /**
     * 客栈申请开通服务
     * @modify songanwei 2016-01-04
     * @modify Paddy 2017-03-14 试用
     * @modify zhangzhen 2017-03-28 活动推广
     * @modify songanwei 2017-05-11 新增 $areaCode $universalTime
     * @param integer $applyId  申请ID
     * @param string $mobile  手机号
     * @param string $name  客栈名称
     * @param integer $cityId 城市ID
     * @param integer $districtId  区域ID
	 * @param string $date  试用日期(可选)
     * @param string $userName 主账号名称
     * @param string $usage 使用状态
     */
    public function handle($applyId, $mobile, $name, $cityId, $districtId, $userName ,$date, $usage, $areaCode = '86', $universalTime = '5', $currencyId = 0) {
        $adminLoginModel = D('AdminLogin');
        $adminHotelModel = D('AdminHotel');
        $hotelEntityModel = D('HotelEntity');
        $hotelApplyModel = D('HotelApply');

        $hotelApplyDetail = $hotelApplyModel->getInfo($applyId);
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if ($adminLogin) {
            // 客栈申请 用户存在逻辑
            $hasUserRight = $adminLogin['status'];
            $userId = $adminLogin['id'];
            // 添加客栈
            $hotelEntityModel->startTrans();
            $commit = true;
            // 判断是否是锁掌柜同步美住创建客栈---申请  添加集群
            $communityno = $hotelApplyDetail['communityno'] != 0 && $hotelApplyDetail['community_id'] != 0 ? $hotelApplyDetail['communityno'] : 0;
            $addResult = $hotelEntityModel->addInfo($name, $cityId, $districtId, $date, 0, $usage, $universalTime, $communityno);
            if (!$addResult) {
                $commit = false;
            }
            $hotelId = $addResult;

            // 添加客栈默认货币
            if ($commit && $currencyId != 0) {
                $currencyHotelModel = D('CurrencyHotel');
                $addResult = $currencyHotelModel->addDefaultCurrency($hotelId, $currencyId, 1);
                if ($addResult == false) {
                    $commit = false;
                }
            }

            //经销商所属客户添加客栈设为已过期
            if ($commit && $hasUserRight==4) {
                $dealerAdmin = D('DealerAdmin')->getInfoByUser($userId);
                $dealerLogin = D('DealerLogin')->getInfo($dealerAdmin['dealerlogin_id']);
                $addResult = $hotelEntityModel->setActive($hotelId, date("Y-m-d",strtotime("-1 day")) ,$dealerLogin['enddate']);
                if (empty($addResult)) {
                    $commit = false;
                }
            }

            // 判断是否是锁掌柜同步美住创建客栈---申请  添加同步记录
            if ($commit && $hotelApplyDetail['communityno'] != 0 && $hotelApplyDetail['community_id'] != 0) {
                $hotelSynModel = D('HotelSyn');
                $addResult = $hotelSynModel->addInfo($hotelId,$hotelApplyDetail['communityno'],$hotelApplyDetail['community_id'],$userId);
                if (empty($addResult)) {
                    $commit = false;
                }
            }

            // 判断是否是锁掌柜同步美住创建客栈---申请  添加同步记录
            if($commit && $hotelApplyDetail['communityno'] != 0 && $hotelApplyDetail['community_id'] != 0) {
                Vendor('phpRPC.phprpc_client');
                $client = new \PHPRPC_Client('http://' . QRMASTER_URL . '/Extend/Syn');
                $client->setEncryptMode(3);
                $sendData = array(
                    'flag' => 'uclbrt',
                    'time' => time(),
                    'm_adminlogin_id' => $userId,
                    'm_adminlogin_mobile' => $adminLogin['mobile'],
                    'm_hotelentity_id' => $hotelId,
                    'm_hotelentity_name' => $name,
                    'q_communityentity_id' => $hotelApplyDetail['community_id'],
                );
                $clientData = $client->notifyCommunitySynchronized($sendData);
                if (empty($clientData)) {
                    $commit = false;
                }
            }

            // 添加客栈信息记录
            if ($commit) {
                $hotelInfoModel = D('HotelInfo');
                $addResult = $hotelInfoModel->addInfo($hotelId);
                if (empty($addResult)) {
                    $commit = false;
                }
            }

            // 添加客栈-人记录
            if ($commit) {
                $addResult = $adminHotelModel->addInfo($hotelId, $userId, 1);
                if (!$addResult) {
                    $commit = false;
                }
            }

            // 添加系统预设数据
            if ($commit) {
                $resourceInfo = $this->getResource();

                $channelData = array();
                foreach ($resourceInfo['channel'] as $channel) {
                    array_push($channelData,
                            array(
                        'hotelentity_id' => $hotelId,
                        'name' => $channel,
                        'type' => 1,
                        'status' => NOT_DELETE,
                    ));
                }
                unset($channel);

                $payData = array();
                foreach ($resourceInfo['pay'] as $pay) {
                    array_push($payData,
                            array(
                        'hotelentity_id' => $hotelId,
                        'name' => $pay,
                        'type' => 1,
                        'status' => NOT_DELETE,
                    ));
                }
                unset($pay);

                if (!empty($channelData)) {
                    $hotelChannelModel = D('HotelChannel');
                    $addResult = $hotelChannelModel->addAllInfo($channelData);
                    if (!$addResult) {
                        $commit = false;
                    }
                }

                if ($commit && !empty($payData)) {
                    $hotelPayModel = D('HotelPay');
                    $addResult = $hotelPayModel->addAllInfo($payData);
                    if (!$addResult) {
                        $commit = false;
                    }
                }

                $noteModel = D('Note');
                $notes = $noteModel->getAll();
                //添加客栈记一笔项目
                if ($commit && $notes) {
                    $hotelNoteModel = D('HotelNote');
                    foreach ($notes as $note) {
                        $hotelNoteData[] = array(
                            'hotelentity_id' => $hotelId,
                            'name' => $note['name'],
                            'type' => $note['type'],
                        );
                    }
                    unset($note);
                    $result = $hotelNoteModel->addAll($hotelNoteData);
                    if ($result == false) {
                        $commit = false;
                    }
                }
            }

            //酒店推广剩余数量减一
            if ($commit && $usage === 1) {
                $redisUtil = new \Redis();
                $redisUtil->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'));
                $redisUtil->auth(C('REDIS_AUTH_PASSWORD'));
                $rest = $redisUtil->get('hotelrest');
                if (!empty($rest)) {
                    $redisUtil->decr('hotelrest');
                }
            }

            //更新客栈申请状态
            if ($commit) {
                $result = $hotelApplyModel->setStatus($applyId, 1);
                if ($result == false) {
                    $commit = false;
                }
            }

            //会员设置为共享时，添加会员信息
            if($commit){
                $vipInitModel = D('VipInit');
                $vipInitInfo = $vipInitModel->getInfoByAdmin($userId);
                if($vipInitInfo['share'] == '1'){
                    $adminHotelInfos = $adminHotelModel->getInfosByAdmin($userId);
                    $vipInfoModel = D('VipInfo');
                    $vipInfos = $vipInfoModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                    $newVipInfo = array();
                    foreach ($vipInfos as $key => $vipInfo) {
                        $addResult = $vipInfoModel->addInfo($vipInfo['name'], $hotelId, $vipInfo['auto'], $vipInitInfo['level'], $vipInfo['levelrule'], $vipInitInfo['discount'], $vipInfo['discountrule']);
                        if (!$addResult) {
                            $commit = false;
                            break;
                        }
                        // 新客栈的vip信息
                        array_push($newVipInfo, array(
                            'vipInfoId' => $addResult,
                            'name' => $vipInfo['name'],
                        ));
                    }
                    $newVipInfo = getArrayValueAsIndex($newVipInfo, 'name');
                    if ($commit) {
                        $vipUserModel = D('VipUser');
                        $vipUserInfoModel = D('VipUserInfo');
                        $vipUserCardModel = D('VipUserCard');
                        $vipUserCardRecordModel = D('VipUserCardRecord');
                        $vipUsers = $vipUserModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);

                        // 获取支付方式id
                        $hotelIds = array_column($vipUsers, 'hotelentity_id');
                        array_push($hotelIds, $hotelId);
                        $hotelPayModel = D('HotelPay');
                        $hotelpayInfo = $hotelPayModel->getInfoByHotel($hotelIds);
                        $hotelpayInfo = getArrayValueAsIndex($hotelpayInfo, 'hotelentity_id', true);
                        foreach ($hotelpayInfo as $key => &$hotelpayItem) {
                            $hotelpayItem = getArrayValueAsIndex($hotelpayItem, 'id');
                        }
                        unset($hotelpayItem);

                        foreach ($vipUsers as $key => $vipUser) {
                            // 获取原来会员等级名称
                            $vipInfos = $vipInfoModel->getInfoById($vipUser['vipinfo_id']);
                            $vipInfoId = isset($newVipInfo[$vipInfos['name']]) ? $newVipInfo[$vipInfos['name']]['vipInfoId'] : '0';

                            $vipUserId = $addResult = $vipUserModel->addInfo($hotelId, $vipInfoId, $vipUser['name'], $vipUser['mobile'], $vipUser['identity'], $vipUser['areacode']);
                            $vipUserInfo = $vipUserInfoModel->getInfoByUserId($vipUser['id']);
                            $addResult=$vipUserInfoModel->addInfo($addResult,$vipUserInfo['gender'],$vipUserInfo['birthday'],$vipUserInfo['nation'],$vipUserInfo['address'],$vipUserInfo['wechat'],$vipUserInfo['remark']);
                            if (!$addResult) {
                                $commit = false;
                                break;
                            }

                            $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUser['id']);
                            $price = isset($vipUserCardInfo['price']) ? $vipUserCardInfo['price'] : '0.00';
                            $addResult = $vipUserCardModel->addVipUserCardInfo($hotelId, $vipUserId, $price, $userId, $userId);
                            if (!$addResult) {
                                $commit = false;
                                break;
                            }

                            // 添加会员充值与消费记录
                            $addRecordData = array();
                            $vipUserCardRecordInfo = $vipUserCardRecordModel->getVipCardRecord($vipUser['id']);
                            foreach ($vipUserCardRecordInfo as $key => $vipUserCardRecordItem) {
                                $payTypeId = $vipUserCardRecordItem['pay_type'];
                                foreach ($hotelpayInfo[$hotelId] as $key => $hotelpayItem) {
                                    if ($hotelpayItem['name'] == $hotelpayInfo[$vipUser['hotelentity_id']][$payTypeId]['name']) {
                                        $payTypeId = $hotelpayItem['id'];
                                    }
                                }
                                unset($hotelpayItem);
                                // 记录数据
                                array_push($addRecordData, array(
                                    'hotelentity_id' => $hotelId, // 当前操作客栈
                                    'vipuser_id' => $vipUserId,
                                    'price' => $vipUserCardRecordItem['price'],
                                    'change_price' => $vipUserCardRecordItem['change_price'],
                                    'pay_type' => isset($payTypeId) ? $payTypeId : '0',
                                    'remark' => $vipUserCardRecordItem['remark'],
                                    'creator' => $userId,
                                    'operator' => $userId,
                                    'createtime' => $vipUserCardRecordItem['createtime'],
                                    'updatetime' => $vipUserCardRecordItem['updatetime'],
                                ));
                            }
                            unset($vipUserCardRecordItem);

                            if ($commit && !empty($addRecordData)) {
                                $addResult = $vipUserCardRecordModel->addAll($addRecordData);
                                if (empty($addResult)) {
                                    $commit = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if ($commit) {
                $hotelEntityModel->commit();
                //如果是经销商下的客户添加客栈，则发短信提醒
                if($hasUserRight == 4){
                    $adminLogin = D('AdminLogin')->getInfo($userId);
                    if ($dealerLogin['areacode'] == '86') {
                        $smsUtil = new \Org\Util\Sms();
                        $smsUtil->sendAddHotelToDealer($dealerLogin['mobile'], $adminLogin['name'], $adminLogin['mobile'], $name);
                    } else {
                        $smsUtil = new \Org\Util\yunPian();
                        $smsUtil->sendAddHotelToDealer($dealerLogin['areacode'], $dealerLogin['mobile'], $adminLogin['name'], $adminLogin['mobile'], $name);
                    }
                }
                return true;
            } else {
                $hotelEntityModel->rollback();
                returnJson(403, 123, '开通服务失败');
            }
        } else {
            // 客栈申请 用户不存在逻辑
            //查询后端默认客栈支付方式、渠道数据
            $payModel = D('Pay');
            $channelModel = D('Channel');
            $noteModel = D('Note');

            $pays = $payModel->getAll();
            $channels = $channelModel->getAll();
            $notes = $noteModel->getAll();

            //开启事务处理
            $hotelEntityModel->startTrans();
            $commit = true;
            //添加客栈数据
            $result = $hotelId = $hotelEntityModel->addInfo($name, $cityId, $districtId, $date, 0, $usage, $universalTime);
            if ($result == false) {
                $commit = false;
            }

            // 添加客栈信息记录
            if ($commit) {
                $hotelInfoModel = D('HotelInfo');
                $addResult = $hotelInfoModel->addInfo($hotelId);
                if (empty($addResult)) {
                    $commit = false;
                }
            }

            //酒店推广剩余数量减一
            if ($commit && $usage === 1) {
                $redisUtil = new \Redis();
                $redisUtil->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'));
                $redisUtil->auth(C('REDIS_AUTH_PASSWORD'));
                $rest = $redisUtil->get('hotelrest');
                if (!empty($rest)) {
                    $redisUtil->decr('hotelrest');
                }
            }
            //添加客栈支付方式
            if ($commit && $pays) {
                $hotelPayModel = D('HotelPay');
                foreach ($pays as $pay) {
                    $hotelPayData[] = array(
                        'hotelentity_id' => $hotelId,
                        'name' => $pay['name'],
                        'type' => 1
                    );
                }
                unset($pay);
                $result = $hotelPayModel->addAll($hotelPayData);
                if ($result == false) {
                    $commit = false;
                }
            }

            //添加客栈默认渠道数据
            if ($commit && $channels) {
                $hotelChannelModel = D('HotelChannel');
                foreach ($channels as $channel) {
                    $hotelChannelData[] = array(
                        'hotelentity_id' => $hotelId,
                        'name' => $channel['name'],
                        'type' => 1
                    );
                }
                unset($channel);
                $result = $hotelChannelModel->addAll($hotelChannelData);
                if ($result == false) {
                    $commit = false;
                }
            }

            //添加客栈记一笔项目
            if ($commit && $notes) {
                $hotelNoteModel = D('HotelNote');
                foreach ($notes as $note) {
                    $hotelNoteData[] = array(
                        'hotelentity_id' => $hotelId,
                        'name' => $note['name'],
                        'type' => $note['type'],
                    );
                }
                unset($note);
                $result = $hotelNoteModel->addAll($hotelNoteData);
                if ($result == false) {
                    $commit = false;
                }
            }

            //更新客栈申请状态
            if ($commit) {
                $result = $hotelApplyModel->setStatus($applyId, 1);
                if ($result == false) {
                    $commit = false;
                }
            }

            if ($adminLogin) {

                //添加账号、客栈关系数据
                if ($commit) {
                    $result = $adminHotelModel->addInfo($hotelId, $adminLogin['id'], 1);
                    if ($result == false) {
                        $commit = false;
                    }
                }
                /*
                if($date && $commit){
                    $result = $adminLoginModel->saveInfo($adminLogin['id'],
                            array(
                                'status' => 1,
                                'endtime' => date('Y-m-d',strtotime('+7 day'))
                            )
                        );
                    if ($result == false) {
                        $commit = false;
                    }   
                }
                */
                if ($commit) {
                    $hotelEntityModel->commit();
                } else {
                    $hotelEntityModel->rollback();
                    returnJson(403, 123, '开通服务失败');
                }
            } else {
                //未注册用户
                $password = getRandomPassword();
                $hotelEntityModel->startTrans();
                $commit = true;
                //添加主账号
                $result = $userId = $adminLoginModel->addInfo($mobile, hash('sha256', $password), $userName, null, $areaCode);
                if ($result == false) {
                    $commit = false;
                }
                
                /*
                if($date && $commit){
                    $result = $adminLoginModel->saveInfo($userId,
                            array(
                                'status' => 1,
                                'endtime' => date('Y-m-d',strtotime('+7 day'))
                            )
                        );
                    if ($result == false) {
                        $commit = false;
                    }   
                }
                */
                
                //添加账号、客栈关系数据
                if ($commit) {
                    $result = $adminHotelModel->addInfo($hotelId, $userId, 1);
                    if ($result == false) {
                        $commit = false;
                    }
                }

                if ($commit) {
                    $adminInfoModel = D('AdminInfo');
                    $result = $adminInfoModel->addInfo($userId);
                    if ($result == false) {
                        $commit = false;
                    }
                }
                if ($commit) {
                    $hotelEntityModel->commit();
                    //发送未注册短信通知
                    if ($areaCode == '86') {
                        $sms = new \Org\Util\Sms();
                        $sms->sendNotReg($mobile, $password);
                    } else {
                        $sms = new \Org\Util\yunPian();
                        $sms->sendNotReg($areaCode, $mobile, $password);
                    }
                } else {
                    $hotelEntityModel->rollback();
                    returnJson(403, 123, '开通服务失败');
                }
            }
        }
    }
    /**
     * 经销商客栈申请开通服务
     * @modify zhangzhen 2017-01-05
     * @modify wenhui 2017-06-05 新增区号 时区
     * @param integer $applyId  申请ID
     * @param string $mobile  手机号
     * @param string $hotelName  客栈名称
     * @param integer $cityId 城市ID
     * @param integer $districtId  区域ID
     * @param string $userName 主账号名称
     * @param string $enddate  到期时间
     * @param string $dealerId 经销商Id
     * @param string $areaCode 手机区号
     * @param string $universaltimeId 时区id
     */
    public function passDealerHotel($applyId, $mobile, $hotelName, $cityId, $districtId, $userName ,$enddate ,$dealerId, $areaCode = '86', $universaltimeId = '5', $usage = '1', $currencyId = 0) {
        //检查用户是否已注册
        $adminLoginModel = D('AdminLogin');
        $adminHotelModel = D('AdminHotel');
        $hotelEntityModel = D('HotelEntity');
        $hotelApplyModel = D('HotelApply');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        $hotelApplyDetail = $hotelApplyModel->getInfo($applyId);

        if ($adminLogin) {
            //检查用户是否已存在此客栈
            $adminHotels = $adminHotelModel->getInfosByAdmin($adminLogin['id']);
            foreach ($adminHotels as $adminHotel) {
                $hotelNameResult = $hotelEntityModel->getName($adminHotel['hotelentity_id']);
                if ($hotelNameResult == $hotelName) {
                    returnJson(403, 123, '客栈已经存在');
                }
            }
        }

        $enddate = $hotelApplyDetail['enddate'] != '0000-00-00' ? $hotelApplyDetail['enddate'] : $enddate;
        //查询后端默认客栈支付方式、渠道数据
        $payModel = D('Pay');
        $channelModel = D('Channel');

        $pays = $payModel->getAll();
        $channels = $channelModel->getAll();

        //开启事务处理
        $hotelEntityModel->startTrans();
        $commit = true;
        //添加客栈数据
        $result = $hotelId = $hotelEntityModel->addInfo($hotelName, $cityId, $districtId, $enddate, 0, $usage, $universaltimeId);
        if ($result == false) {
            $commit = false;
        }

        // 添加客栈默认货币
        if ($commit && $currencyId != 0) {
            $currencyHotelModel = D('CurrencyHotel');
            $addResult = $currencyHotelModel->addDefaultCurrency($hotelId, $currencyId, 1);
            if ($addResult == false) {
                $commit = false;
            }
        }

        // 添加客栈信息记录
        if ($commit) {
            $hotelInfoModel = D('HotelInfo');
            $addResult = $hotelInfoModel->addInfo($hotelId);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        //酒店推广剩余数量减一
        if ($commit) {
            $redisUtil = new \Redis();
            $redisUtil->connect(C('REDIS_SERVERIP'), C('REDIS_SERVERPORT'));
            $redisUtil->auth(C('REDIS_AUTH_PASSWORD'));
            $rest = $redisUtil->get('hotelrest');
            if (!empty($rest)) {
                $redisUtil->decr('hotelrest');
            }
        }
        //添加客栈支付方式
        if ($commit && $pays) {
            $hotelPayModel = D('HotelPay');
            foreach ($pays as $pay) {
                $hotelPayData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $pay['name'],
                    'type' => 1
                );
            }
            unset($pay);
            $result = $hotelPayModel->addAll($hotelPayData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加客栈默认渠道数据
        if ($commit && $channels) {
            $hotelChannelModel = D('HotelChannel');
            foreach ($channels as $channel) {
                $hotelChannelData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $channel['name'],
                    'type' => 1
                );
            }
            unset($channel);
            $result = $hotelChannelModel->addAll($hotelChannelData);
            if ($result == false) {
                $commit = false;
            }
        }

        //更新客栈申请状态
        if ($commit) {
            $hotelApplyModel = D('HotelApply');
            $result = $hotelApplyModel->setStatus($applyId, 1);
            if ($result == false) {
                $commit = false;
            }
        }

        if ($adminLogin) {
            //会员设置为共享时，添加会员信息
            if($commit){
                $vipInitModel = D('VipInit');
                $userId = $adminLogin['id'];
                $vipInitInfo = $vipInitModel->getInfoByAdmin($userId);
                if($vipInitInfo['share'] == '1'){
                    $adminHotelInfos = $adminHotelModel->getInfosByAdmin($userId);
                    $vipInfoModel = D('VipInfo');
                    $vipInfos = $vipInfoModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                    $newVipInfo = array();
                    foreach ($vipInfos as $key => $vipInfo) {
                        $addResult = $vipInfoModel->addInfo($vipInfo['name'], $hotelId, $vipInfo['auto'], $vipInitInfo['level'], $vipInfo['levelrule'], $vipInitInfo['discount'], $vipInfo['discountrule']);
                        if (!$addResult) {
                            $commit = false;
                            break;
                        }
                        // 新客栈的vip信息
                        array_push($newVipInfo, array(
                            'vipInfoId' => $addResult,
                            'name' => $vipInfo['name'],
                        ));
                    }
                    $newVipInfo = getArrayValueAsIndex($newVipInfo, 'name');
                    if ($commit) {
                        $vipUserModel = D('VipUser');
                        $vipUserInfoModel = D('VipUserInfo');
                        $vipUserCardModel = D('VipUserCard');
                        $vipUserCardRecordModel = D('VipUserCardRecord');
                        $vipUsers = $vipUserModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);

                        // 获取支付方式id
                        $hotelIds = array_column($vipUsers, 'hotelentity_id');
                        array_push($hotelIds, $hotelId);
                        $hotelPayModel = D('HotelPay');
                        $hotelpayInfo = $hotelPayModel->getInfoByHotel($hotelIds);
                        $hotelpayInfo = getArrayValueAsIndex($hotelpayInfo, 'hotelentity_id', true);
                        foreach ($hotelpayInfo as $key => &$hotelpayItem) {
                            $hotelpayItem = getArrayValueAsIndex($hotelpayItem, 'id');
                        }
                        unset($hotelpayItem);

                        foreach ($vipUsers as $key => $vipUser) {
                            // 获取原来会员等级名称
                            $vipInfos = $vipInfoModel->getInfoById($vipUser['vipinfo_id']);
                            $vipInfoId = isset($newVipInfo[$vipInfos['name']]) ? $newVipInfo[$vipInfos['name']]['vipInfoId'] : '0';

                            $vipUserId = $addResult = $vipUserModel->addInfo($hotelId, $vipInfoId, $vipUser['name'], $vipUser['mobile'], $vipUser['identity'], $vipUser['areacode']);
                            $vipUserInfo = $vipUserInfoModel->getInfoByUserId($vipUser['id']);
                            $addResult=$vipUserInfoModel->addInfo($addResult,$vipUserInfo['gender'],$vipUserInfo['birthday'],$vipUserInfo['nation'],$vipUserInfo['address'],$vipUserInfo['wechat'],$vipUserInfo['remark']);
                            if (!$addResult) {
                                $commit = false;
                                break;
                            }

                            $vipUserCardInfo = $vipUserCardModel->getInfoByVipUserId($vipUser['id']);
                            $price = isset($vipUserCardInfo['price']) ? $vipUserCardInfo['price'] : '0.00';
                            $addResult = $vipUserCardModel->addVipUserCardInfo($hotelId, $vipUserId, $price, $userId, $userId);
                            if (!$addResult) {
                                $commit = false;
                                break;
                            }

                            // 添加会员充值与消费记录
                            $addRecordData = array();
                            $vipUserCardRecordInfo = $vipUserCardRecordModel->getVipCardRecord($vipUser['id']);
                            foreach ($vipUserCardRecordInfo as $key => $vipUserCardRecordItem) {
                                $payTypeId = $vipUserCardRecordItem['pay_type'];
                                foreach ($hotelpayInfo[$hotelId] as $key => $hotelpayItem) {
                                    if ($hotelpayItem['name'] == $hotelpayInfo[$vipUser['hotelentity_id']][$payTypeId]['name']) {
                                        $payTypeId = $hotelpayItem['id'];
                                    }
                                }
                                unset($hotelpayItem);
                                // 记录数据
                                array_push($addRecordData, array(
                                    'hotelentity_id' => $hotelId, // 当前操作客栈
                                    'vipuser_id' => $vipUserId,
                                    'price' => $vipUserCardRecordItem['price'],
                                    'change_price' => $vipUserCardRecordItem['change_price'],
                                    'pay_type' => isset($payTypeId) ? $payTypeId : '0',
                                    'remark' => $vipUserCardRecordItem['remark'],
                                    'creator' => $userId,
                                    'operator' => $userId,
                                    'createtime' => $vipUserCardRecordItem['createtime'],
                                    'updatetime' => $vipUserCardRecordItem['updatetime'],
                                ));
                            }
                            unset($vipUserCardRecordItem);

                            if ($commit && !empty($addRecordData)) {
                                $addResult = $vipUserCardRecordModel->addAll($addRecordData);
                                if (empty($addResult)) {
                                    $commit = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if($commit){
                $result = $adminLoginModel->saveInfo($adminLogin['id'],
                        array(
                            'status' => 4,
                        )
                    );
          
                if ($result == false) {
                    $commit = false;
                }  
            }

            //添加账号、客栈关系数据
            if ($commit) {
                $result = $adminHotelModel->addInfo($hotelId, $adminLogin['id'], 1);
                if ($result == false) {
                    $commit = false;
                }
            }

            //添加账号、经销商关系数据
            if ($commit) {
                $dealerAdminModel = D('DealerAdmin');
                $result = $dealerAdminModel->addInfo($dealerId, $adminLogin['id']);
                if ($result == false) {
                    $commit = false;
                }
            }

            if ($commit) {
                $hotelEntityModel->commit();
                $hotelApplyInfo = $hotelApplyModel->getInfo($applyId);
                $dealerLogin= D('DealerLogin')->getInfo($hotelApplyInfo['dealerlogin_id']);
                if ($dealerLogin['areacode'] == '86') {
                    $sms = new \Org\Util\Sms();
                    $sms->sendDealerHotelPass($dealerLogin['mobile'], $hotelApplyInfo['hotelname'], $hotelApplyInfo['username']);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $sms->sendDealerHotelPass($dealerLogin['areacode'], $dealerLogin['mobile'], $hotelApplyInfo['hotelname'], $hotelApplyInfo['username']);
                }
            } else {
                $hotelEntityModel->rollback();
                returnJson(403, 123, '开通服务失败');
            }
        } else {
            //未注册用户
            $password = getRandomPassword();
            $hotelEntityModel->startTrans();
            $commit = true;
            //添加主账号
            $result = $userId = $adminLoginModel->addInfo($mobile, hash('sha256', $password), $userName, 4, $areaCode);
            if ($result == false) {
                $commit = false;
            }
            //添加账号、客栈关系数据
            if ($commit) {
                $result = $adminHotelModel->addInfo($hotelId, $userId, 1);
                if ($result == false) {
                    $commit = false;
                }
            }
            //添加账号、经销商关系数据
            if ($commit) {
                $dealerAdminModel = D('DealerAdmin');
                $result = $dealerAdminModel->addInfo($dealerId, $userId);
                if ($result == false) {
                    $commit = false;
                }
            }

            if ($commit) {
                $adminInfoModel = D('AdminInfo');
                $result = $adminInfoModel->addInfo($userId);
                if ($result == false) {
                    $commit = false;
                }
            }
            if ($commit) {
                $hotelEntityModel->commit();
                //发送未注册短信通知
                if ($areaCode == '86') {
                    $sms = new \Org\Util\Sms();
                    $sms->sendNotReg($mobile, $password);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $sms->yunPiansendNotReg($areaCode, $mobile, $password);
                }

                $hotelApplyInfo = $hotelApplyModel->getInfo($applyId);
                $dealerLogin= D('DealerLogin')->getInfo($hotelApplyInfo['dealerlogin_id']);
                if ($dealerLogin['areacode'] == '86') {
                    $sms = new \Org\Util\Sms();
                    $sms->sendDealerHotelPass($dealerLogin['mobile'], $hotelApplyInfo['hotelname'], $hotelApplyInfo['username']);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $sms->sendDealerHotelPass($dealerLogin['areacode'], $dealerLogin['mobile'], $hotelApplyInfo['hotelname'], $hotelApplyInfo['username']);
                }
            } else {
                $hotelEntityModel->rollback();
                returnJson(403, 123, '开通服务失败');
            }
        }
    }

    /**
     * 获取区号时区数据
     * @modify wenhui 2017-06-16
     * @return array $data 时区数据
     */
    public function universalTimeList() {

        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_PUBLIC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => 'uclbrt',
            'time' => time(),
        );

        $result = $client->getAreaCode($RPCData);
        if (!is_array($result)) {
            return array(
                array(
                    'fullName' => '中国',
                    'firstName' => 'C',
                    'areaCode' => '86',
                    'universalTimeId' => '5',
                    'universalTimeUtc' => 'UTC/GMT+8',
                    'universalTimeName' => '中国/China',
                    'universalTimeTimezone' => 'GMT+8',
                ),
            );
        } else {
            return $result['cn'];
        }
    }

    /**
     * 获取系统默认客栈资源
     * @modify trainyao 2016-01-09    创建
     */
    protected function getResource() {
        $return = array();
        $channelModel = D('Channel');
        $return['channel'] = $channelModel->getInfo();
        $return['channel'] = array_column($return['channel'], 'name');

        $payModel = D('Pay');
        $return['pay'] = $payModel->getInfo();
        $return['pay'] = array_column($return['pay'], 'name');

        return $return;
    }
}
